<script setup lang="ts">
import CenterTitle from '~/components/CenterTitle/index.vue'
import ItemSquare from '~/components/ItemSquare/index.vue'
import Tabs from '~/components/Tabs/index.vue'
import { useAuth } from '~/stores/auth/index'
import PaginationAlbum from '~/components/PaginationAlbum/index.vue'
import APIMaterial from '~/api/material'
import type { MaterialType, MaterialListResult } from '~/api/material/types'

definePageMeta({
    showSmallSearchBox: true,
})

const type = shallowRef<MaterialType>('all')
const { token, info } = storeToRefs(useAuth())

const tabsList = reactive([{
    label: '全部', value: 'all'
}, {
    label: '关注', value: 'concern'
}, {
    label: '视频', value: 'video'
}, {
    label: '图片', value: 'picture'
}, {
    label: '音乐', value: 'music'
}, {
    label: '字体', value: 'font'
}])

function onChange(item: any) {
    type.value = item.value
}

const queryParams = ref<PageQuery>({
    page: 1,
    limit: 8
})

const list = ref<MaterialListResult[]>([])
const total = shallowRef<number>(0)
const loading = shallowRef<boolean>(false)

function getList() {
    if (token.value) {
        loading.value = true
        APIMaterial.getLoginMaterial(type.value, queryParams.value).then(({ total: count, data }) => {
            list.value = data
            total.value = count
        }).finally(() => {
            loading.value = false
        })
    } else {
        loading.value = true
        APIMaterial.getMaterial(type.value, queryParams.value).then(({ total: count, data }) => {
            list.value = data
            total.value = count
        }).finally(() => {
            loading.value = false
        })
    }
}

watch(type, () => {
    list.value = []
    getList()
}, { immediate: true })

const itemSquareListRef = ref<any[]>([])

function onPlay(id: number) {
    itemSquareListRef.value.forEach((item: any) => {
        item?.handleSuspend()
    })

    itemSquareListRef.value.forEach((item: any) => {
        if (item.item.id == id) {
            item.onPlay()
        }
    })
}

</script>

<template>
    <div class="material">
        <CenterTitle title="素材广场" englishTitle="SU CAI GUANG CHANG" />
        <Tabs :list="tabsList" @onChange="onChange" />
        <div class="list" v-loading="loading">
            <el-empty description="暂无内容" v-if="list.length == 0" />
            <ItemSquare v-for="(item, index) in list" :key="item.id" :item="item" ref="itemSquareListRef"
                @on-play="onPlay(item.id)" />
        </div>
        <div class="pagination">
            <PaginationAlbum :total="total" v-model:current-page="queryParams.page" :page-size="queryParams.limit"
                @get-list="getList" />
        </div>
    </div>
</template>

<style lang="less" scoped>
.material {
    box-sizing: border-box;
    width: 1340px;
    padding: 0 20px;
    margin: 0 auto;

    .pagination {
        margin-top: 30px;
    }

    .list {
        margin-top: 30px;
        border-top: 1px solid #E8E8E8;
    }
}
</style>